#include "fan.h"
#include "tim.h"
#include "adc.h"


uint32_t temp_buf[20] = {0};
FAN_DATA fan_data = {
    .fan_duty = 0,
    .fan_duty_target = 30,
    .fan_temperature_target = 400
};

PID temperature_pid = {
    .kp = 2,
    .ki = 0.3,
    .kd = 3,
    .target = 25,
    .max_change_i = 500,
    .max_output = 500
};

void fan_init(void)
{
    //开启风枪pwm
    HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_4);
    //开启热电偶pwm
    HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_4);
    //开启温度ADC——DMA
    HAL_ADC_Start_DMA(&hadc1, temp_buf, 20);
}

/**
 * 设置风枪风机的pwm
 * 参数：duty:0-100
 */
void fan_set_pwm(uint16_t duty)
{
    if(duty > 100) duty = 100;
    fan_data.fan_duty = duty;
    if(duty == 0)
    {
        __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_4, 0);
    }
    else{
        __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_4, 500 + 5*duty);
    }
    
}

// 设置风枪热电偶的pwm
void heat_set_pwm(uint16_t duty)
{
    __HAL_TIM_SET_COMPARE(&htim4, TIM_CHANNEL_4, duty);
}

//获取当前的风枪的温度值
float fan_temp_getval(void)
{
    float temperature = 0;
    for(uint8_t i = 0; i<10; i++)
    {
       temperature += temp_buf[i];
    }
    temperature = ((temperature / 10) * 0.1374f);

    return temperature;
}


PID temperature_pid_control(uint16_t temperature_target)
{
    int PWM = 0;
    PWM = pid_calc(&temperature_pid, temperature_target, fan_temp_getval());

    if(PWM < 0 ) PWM = 0;
    heat_set_pwm(PWM);

    return temperature_pid;
}

